from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from meiduo_mall import settings
from users.models import User


def generate_verify_email_url(user_id,email):
    serializer = Serializer(settings.SECRET_KEY,3600)

    data = {
        'user_id':user_id,
        'email': email
    }

    token = serializer.dumps(data)
    verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s'%token.decode()

    return verify_url


def check_verify_email_token(token):
    serializer = Serializer(settings.SECRET_KEY, 3600)
    try:
        # 加载token
        result = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = result.get('user_id')
        email = result.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            user = None
        else:
            return user


# from django.core.email import send_mail
#
# def send_verify_mail(to_email,verify_url):
#     subject = '美多商場激活郵件'
#     message = ''
#     from_email = '美多商城<m18236417889@163.com>'
#
#     html_message = '<p>尊敬的用户您好！</p>' \
#                    '<p>感谢您使用美多商城。</p>' \
#                    '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
#                    '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
#
#     send_mail(subject=subject,
#               message=message,
#               from_email=from_email,
#               html_message=html_message)

# def generate_verify_email_url(self):
#
#     serializer = Serializer(settings.SECRET_KEY, 3600)
#
#     # 加载用户信息
#     token = serializer.dumps({'user_id': self.id, 'email': self.email})
#     # 注意拼接的过程中对 token进行decode操作
#     verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()
#
#     return verify_url

